﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic.WeiXin;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Repository;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Repository.WeiXin;
using Atmk.WaterMeter.MIS.Datas;
using Atmk.WaterMeter.MIS.Entities.Models;
using Atmk.WaterMeter.MIS.Logic.Mock;
using NLog;

namespace Atmk.WaterMeter.MIS.Logic.WeiXin
{
    public class WxAccountLogic : IWxAccountLogic
    {
        private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
        private readonly IAccountRepository _accountRepository;
        private readonly IOwnerRepository _ownerRepository;
        private readonly IWxSrRelationRepositoryWrite _wxSrRelationRepositoryWrite;
        private readonly IWxSrRelationRepositoryRead _wxSrRelationRepositoryRead;

        public WxAccountLogic(
            IAccountRepository accountRepository,
            IOwnerRepository ownerRepository,
            IWxSrRelationRepositoryWrite wxSrRelationRepositoryWrite,
            IWxSrRelationRepositoryRead wxSrRelationRepositoryRead
        )
        {
            _accountRepository = accountRepository;
            _ownerRepository = ownerRepository;
            _wxSrRelationRepositoryWrite = wxSrRelationRepositoryWrite;
            _wxSrRelationRepositoryRead = wxSrRelationRepositoryRead;
        }

        /// <summary>
        /// 通过用户id获取账户信息(如果复数，则取首个)
        /// </summary>
        /// <param name="openId"></param>
        /// <param name="meterNumber"></param>
        /// <param name="houseNumber"></param>
        /// <param name="balance"></param>
        /// <param name="meterNo">水表编号，如果有就填上</param>
        /// <returns></returns>
        public Task<bool> SelectAccount(string openId, out string meterNumber, out string houseNumber,
            out decimal balance,
            string meterNo = "")
        {
            meterNumber = "";
            houseNumber = "";
            balance = 0.00m;
            var result = false;
            try
            {
                //获取所有水表号
                if (meterNo == "")
                {
                    var list = SelectAllMeterNumber(openId).Result.ToList();
                    meterNumber = list.Count > 0 ? list.First() : "";
                }
                else
                {
                    meterNumber = meterNo;
                }
                if (meterNumber != "")
                {
                    GetParment(meterNumber, out var owner, out balance);
                    if (owner != null)
                    {
                        houseNumber = owner.HouseNumber;
                        result = true;
                    }
                    //if (account != null)
                    //    balance = account.Balance;
                }
            }
            catch (Exception e)
            {
                _logger.Error(e);
            }
            return Task.Run(() => result);
        }

        /// <summary>
        /// 通过用户id获取水表编号集合--复数时用
        /// </summary>
        /// <param name="openId"></param>
        /// <returns></returns>
        public Task<List<string>> SelectAllMeterNumber(string openId)
        {
            var array = _wxSrRelationRepositoryRead
                .SelectArrayRelations(openId)
                .Select(w => w.Number)
                .ToList();
            return Task.Run(() => array);
        }

        /// <summary>
        /// 添加用户Id和水表的关系记录，并返回该水表所在位置的门牌号和
        /// </summary>
        /// <param name="openId"></param>
        /// <param name="meterNumber"></param>
        /// <param name="houseNumber"></param>
        /// <param name="balance"></param>
        /// <returns></returns>
        public Task<bool> AddAccount(string openId, string meterNumber, out string name, out string houseNumber, out decimal balance)
        {
            houseNumber = "";
            name = "";
            balance = 0.00m;
            var result = false;
            //GetParment(meterNumber, out var owner, out var account);
            try
            {
                using (var _context = ContextBuilder.Build())
                {
                    var meter = _context.Meter.FirstOrDefault(m => m.MeterNumber == meterNumber);
                    if (meter == null)
                    {
                        return Task.Run(() => false);
                    }
                    var owner = _context.Owner.FirstOrDefault(m => m.Id == meter.OwnerId);
                    if (owner == null)
                    {
                        return Task.Run(() => false);
                    }
                    name = owner.Name;
                    //根据业主信息，获取账户信息
                    var orderDetails = _accountRepository.GetAccounts(owner.Id);

                    var accountId = owner.Id;
                    var relation = new WxSrRelations
                    {
                        OpenId = openId,
                        Number = meterNumber,
                        OwnerId = owner.Id,
                        AccountId = accountId
                    };
                    //添加关系记录
                    _wxSrRelationRepositoryWrite.AddWxSrRelation(relation);
                    houseNumber = owner.HouseNumber;
                    if (orderDetails != null)
                        balance = Convert.ToDecimal(orderDetails.Sum(m => m.Money));
                    result = true;
                }
            }
            catch (Exception e)
            {
                _logger.Error(e);
            }
            return Task.Run(() => result);
        }

        //新版 绑定水表
        public bool AddAccount2(string openId,  Meter meter ,Owner owner)
        {
            //GetParment(meterNumber, out var owner, out var account);
            try
            {
                using (var _context = ContextBuilder.Build())
                {
                    var accountId = owner.Id;
                    var relation = new WxSrRelations
                    {
                        OpenId = openId,
                        Number = meter.MeterNumber,
                        OwnerId = owner.Id,
                        AccountId = accountId
                    };
                    //添加关系记录
                    var result=_wxSrRelationRepositoryWrite.AddWxSrRelation(relation);
                    if (result)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            catch (Exception e)
            {
                _logger.Error(e);
                return false;
            }
        }
        public Owner GetOwner(string openId, string meterNumber, out decimal balance)
        {
            balance = 0;
            try
            {
                using (var _context = ContextBuilder.Build())
                {
                    var meter = _context.Meter.FirstOrDefault(m => m.MeterNumber == meterNumber);
                    var owner = meter == null ? null : _context.Owner.FirstOrDefault(m => m.Id == meter.OwnerId);

                    //根据业主信息，获取账户信息
                    var orderDetails = _accountRepository.GetAccounts(owner.Id);
                    if (orderDetails != null)
                        balance = Convert.ToDecimal(orderDetails.Sum(m => m.Money));
                    if (owner == null)
                    {
                        return null;
                    }
                    else
                    {
                        return owner;
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
                return null;
            }
        }
        public List<Meter> GetMeters(string ownerid)
        {
            try
            {
                using (var _context = ContextBuilder.Build())
                {
                    return _context.Meter.Where(m => m.OwnerId == ownerid).ToList();
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex); 
                return null;
            }

        }
        private void GetParment(string meterNumber, out Owner owner, out decimal balance)
        {
            owner = null;
            owner = _ownerRepository.GetOwnersByMeterNo(meterNumber).First();
            //根据业主信息，获取账户信息
            var orderDetails = _accountRepository.GetAccounts(owner.Id);
            //如果没有账户，则金额为0
            if (orderDetails.Count > 0)
            {
                balance = Convert.ToDecimal(orderDetails.Sum(m => m.Money));
            }
            else
            {
                balance = 0;
            }
        }

        /// <summary>
        /// 注销用户Id和水表关系记录
        /// </summary>
        /// <param name="openId"></param>
        /// <param name="meterNumber"></param>
        /// <returns></returns>
        public Task<bool> LogoutAccount(string openId, string meterNumber)
        {
            var result = false;
            try
            {
                //注销关系记录
                result = _wxSrRelationRepositoryWrite.DeleteWxSrRelation(openId, meterNumber);
            }
            catch (Exception e)
            {
                _logger.Error(e);
            }
            return Task.Run(() => result);
        }


    }
}